package com.cloudfun.campusshare.configuration.jpa.specification;

import com.cloudfun.campusshare.configuration.jpa.util.JpaRestrictionBuilder;
import com.cloudfun.campusshare.configuration.jpa.util.RestrictionNames;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 * @author 王溪源
 * @ClassName: PropertySpecification
 * @Description: TODO
 * @Date 2020/8/10 9:24
 **/
public class PropertySpecification<T> implements Specification<T> {
    // 属性名称
    private String propertyName;
    // 值
    private Object value;
    // 约束名称
    private String restrictionName;

    public PropertySpecification(String propertyName, Object value) {
        this.propertyName = propertyName;
        this.value = value;
        this.restrictionName = RestrictionNames.EQ;
    }

    public PropertySpecification(String propertyName, Object value, String restrictionName) {
        this.propertyName = propertyName;
        this.value = value;
        this.restrictionName = restrictionName;
    }

    @Override
    public Predicate toPredicate(Root<T> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
        return criteriaBuilder.and (JpaRestrictionBuilder.getRestriction (propertyName, value, restrictionName, new SpecificationModel (root,
                criteriaQuery, criteriaBuilder)));
    }
}
